<template>
  <div class="shop-info">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="form">
      <el-form-item label="老板姓名" prop="merchantBoss">
        <el-input v-model="form.merchantBoss" placeholder="请输入老板姓名"></el-input>
      </el-form-item>
      <el-form-item label="商户名称" prop="merchantName">
        <el-input v-model="form.merchantName" placeholder="请输入商户名称"></el-input>
      </el-form-item>
      <el-form-item label="经营类型" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择经营类型">
          <el-option v-for="category in categories" :key="category.categoryId" :label="category.categoryName" :value="category.categoryId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商户logo" prop="merchantLogo">
        <el-upload class="avatar-uploader"
                   action="http://localhost:8018/file/uploadAvatar"
                   list-type="picture-card"
                   :on-success="handleLogoSuccess"
                   :show-file-list="false">
          <img v-if="form.merchantLogo" :src="getImgUrl(form.merchantLogo)" class="avatar"  alt=""/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="商户描述" prop="merchantDesc">
        <el-input type="textarea" v-model="form.merchantDesc" placeholder="请输入商户描述"></el-input>
      </el-form-item>
      <el-form-item label="营业执照" prop="businessLicense">
        <el-upload class="avatar-uploader"
                   action="http://localhost:8018/file/uploadAvatar"
                   list-type="picture-card"
                   :on-success="handleLicenseSuccess"
                   :show-file-list="false">
          <img v-if="form.businessLicense" :src="getImgUrl(form.businessLicense)" class="avatar"  alt=""/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入地址"></el-input>
      </el-form-item>
      <el-form-item label="商户状态" prop="merchantStatus">
        <el-radio-group v-model="form.merchantStatus">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">暂停营业</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import {getMerchantByUserId, updateMerchant} from "@/api/merchant";
import {Merchants} from "@/api/merchant/types/merchant.dto.ts";
import {sysStore} from "../../../stores/index.ts";
import {getImgUrl} from "@/utils/common.ts";
import {Plus} from "@element-plus/icons-vue";
import {getCategoryList} from "@/api/article";

// 表单数据
const form = reactive({
  merchantId: 0,
  merchantBoss: '',
  merchantName: '',
  categoryId: 0,
  merchantLogo: '',
  merchantDesc: '',
  businessLicense: '',
  contactPhone: '',
  address: '',
  merchantStatus: 1,
});

interface Category {
  categoryId: number;
  categoryName: string;
}
// 类别选项
const categories = ref<Category[]>([]);

const appStore = sysStore();

onMounted(() => {
  const userId = appStore.userInfo?.id;
  getFormData(userId);
  getCategoryInfo()
})

// 获取类别下拉框的选项
async function getCategoryInfo() {
  const res = await getCategoryList();
  console.log("类别信息：",res)
  if (res.code == 200) {
    categories.value = res.data;
  }

}

// 表单验证规则
const rules = {
  merchantBoss: [{ required: true, message: '请输入老板姓名', trigger: 'blur' }],
  merchantName: [{ required: true, message: '请输入商户名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择经营类型', trigger: 'change' }],
  businessLicense: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
  contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
};

// 表单引用
const formRef = ref<FormInstance>();

// logo上传
const handleLogoSuccess = (response: any) => {
  form.merchantLogo = response.data.url;
};

// 营业执照上传
const handleLicenseSuccess = (response: any) => {
  form.businessLicense = response.data.url;
};

// 获取表单信息
async function getFormData(id: number) {

  const res = await getMerchantByUserId(id);
  console.log("当前商家：",res)
  if (res.code == 200) {
    const data = res.data;
    form.merchantId = data.merchantId;
    form.merchantBoss = data.merchantBoss;
    form.merchantName = data.merchantName;
    form.categoryId = data.categoryId;
    form.merchantLogo = data.merchantLogo;
    form.merchantDesc = data.merchantDesc;
    form.businessLicense = data.businessLicense;
    form.contactPhone = data.contactPhone;
    form.address = data.address;
    form.merchantStatus = data.merchantStatus;
  }
}

// 提交表单
const submitForm = () => {
  formRef.value?.validate( async (valid) => {
    if (valid) {
      const res = await updateMerchant(<Merchants>form);
      if (res.code === 200) {
        ElMessage({ message: '保存成功', type: 'success' });
        getFormData(appStore.userInfo?.id);
      } else {
        ElMessage({ message: '保存失败', type: 'error' });
      }
    } else {
      ElMessage.error('请填写完整表单');
    }
  });
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  form.merchantLogo = '';
  form.businessLicense = '';
};
</script>

<style scoped lang="scss">
.shop-info {
  padding: 20px;
  .form {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background-color: white;

    .el-form-item {
      margin-bottom: 20px;
    }

    .el-input,
    .el-select,
    .el-upload {
      width: 100%;
    }
  }

  .avatar-uploader {
    display: flex;
    justify-content: center;
    margin: 30px 0;

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      width: 150px;
      height: 150px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .avatar {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .avatar-uploader-icon {
    font-size: 32px;
    color: var(--el-text-color-secondary);
  }
}
</style>